package com.wex.app.tools;

import ohos.agp.components.TextField;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;

import java.io.RandomAccessFile;

public class LogUtils {

    // ---------- base ----------

    public LogUtils(Context c) {
        context = c;
    }

    public void append(String s)  {
        appendConsole(s);
        appendLogFile(s);
        if (textFiledAlwaysOn)
            appendTextFiled(s);
    }

    public void appendAll(String s)  {
        appendConsole(s);
        appendLogFile(s);
        appendTextFiled(s);
    }

    public void setTextFiledAlwaysOn(boolean enable) {
        textFiledAlwaysOn = enable;
    }

    private Context context;
    private boolean textFiledAlwaysOn = false;

    // ---------- console ----------

    public void appendConsole(String s) {
        System.out.print("----->> " + s);
    }

    // ---------- logFile ----------

    public void appendLogFile(String s) {
        if (logFile == null)
            return;
        FileTools.write(logFile, s);
    }

    public boolean setLogFile(String file) {
        FileTools.close(logFile);
        logFile = FileTools.openWriter(context, file);
        return logFile == null ? false : true;
    }

    protected void finalize() throws Throwable {
        FileTools.close(logFile);
    }

    private RandomAccessFile logFile = null;

    // ---------- textField ----------

    public void appendTextFiled(String s) {
        if (textField == null)
            return;
        textFieldEvent.append(s);
    }

    public void setTextField(TextField t) {
        textField = t;
        if (textFieldEvent == null)
            textFieldEvent = new TextFieldEvent(EventRunner.getMainEventRunner());
    }

    private class TextFieldEvent extends EventHandler {
        public TextFieldEvent(EventRunner eventRunner) {
            super(eventRunner);
        }
        @Override
        protected void processEvent(InnerEvent event) {
            switch (event.eventId) {
                case 1:
                    if (event.object instanceof String)
                        textField.append((String)(event.object));
                    break;
                default:
                    break;
            }
        }
        public void append(String s) {
            InnerEvent innerEvent = InnerEvent.get(1, s);
            sendEvent(innerEvent, 0, EventHandler.Priority.IMMEDIATE);
        }
    }

    private TextField textField = null;
    private TextFieldEvent textFieldEvent = null;
}
